import axios from 'axios'
import { ElMessage } from 'element-plus'
const NETWORK_ERROR ='网络错误，请稍后重试'
// 创建axios实例对象
const service = axios.create({
    baseURL:'/api',
})

service.interceptors.request.use((req)=>{
    // 自定义header
    // token认证
    return req
})

service.interceptors.response.use((res)=>{
    const {code,data,msg} = res.data
    if( code==200 ){
        return data
    }else{
        // 网络错误
        ElMessage.error(msg||NETWORK_ERROR)
        return Promise.reject(msg||NETWORK_ERROR)
    }
})

// 封装核心函数
function request(options){
    options.method = options.method || 'get'
    if(options.method.toLowerCase() == 'get'){
        options.params =options.data
    }

    return service(options)
}

export default request